<?php
namespace app\admin\model\agent;
use app\admin\model\agent\User as AgentUser;
use app\admin\model\BaseSetting;
use think\Model;
use think\Db;
use utils\Random;

class Agent extends Model
{
    protected $name = 'agent';


    protected static function init()
    {
        self::afterInsert(function ($row) {
            $pk = $row->getPk();
            $row->getQuery()->where($pk, $row[$pk])->update(['pinpai_id' => $row[$pk]]);
        });
    }

    /**
     * 获取代理商信息
     * @param int|null $agentId
     * @throws \think\exception\DbException
     */
    public static function detail($agentId = null)
    {
        return static::get($agentId ?: []);
    }


    public function getNoActiveList($is_recycle = false){
        return $this->where('type','=',1)
            ->whereOr('type','=',2)
            ->where(['active'=>0,'is_delete'=> 0,'is_recycle'=>(int)$is_recycle,'recommend_id'=>['neq',0]])
            ->order(['create_time' => 'desc'])
            ->paginate(15, false, [
                'query' => request()->request()
            ]);
    }



    /**
     * 获取代理商列表
     * @param boolean $is_recycle
     * @return \think\Paginator
     * @throws \think\exception\DbException
     */
    public function getList($is_recycle = false)
    {
        return $this->where('is_recycle', '=', (int)$is_recycle)
            ->where('is_delete', '=', 0)
            ->order(['create_time' => 'desc'])
            ->paginate(15, false, [
                'query' => request()->request()
            ]);

    }


    /**
     * 新增记录
     * @param $data
     * @return bool|mixed
     */
    public function add($data)
    {

        if ($data['password'] !== $data['password_confirm']) {
            $this->error = '确认密码不正确';
            return false;
        }
        if (AgentUser::checkExist($data['user_name'])) {
            $this->error = '品牌商用户名已存在';
            return false;
        }
        $data['salt']=Random::alnum();
        $data['password']=md5(md5($data['password']. $data['salt'].config('salt')));
        $data['user_name']=$data['user_name'];
        return $this->transaction(function () use ($data) {
            // 添加小程序记录
            $this->allowField(true)->save($data);
            // 新增商家用户信息
            (new AgentUser)->add($this['agent_id'], $data);
            return true;
        });
    }


    /**
     * 激活代理商
     * @param bool $agent_id
     * @return false|int
     */
    public function actived($agent_id)
    {

        $data=$this->get($agent_id);
        // 激活代理商,0,城市承运商，1.城市运营商，2.城市合伙人
        if($data['type']==1){
            $finishTime=strtotime("+3 year");
            $cover=BaseSetting::getItemValue('operate_template');

        }else if($data['type']==2){
            $finishTime=strtotime("+2 year");
            $cover=BaseSetting::getItemValue('partner_template');
        }else{
            $finishTime=strtotime("+5 year");
            $cover=0;
        }
        if($data['type']==3){
            //代言人
            if($data['agent_check_status']==0){
                return -1;//需要代理商先通过
            }
        }
        return $this->transaction(function () use ($agent_id,$finishTime,$cover) {
           $this->where(['agent_id'=>$agent_id])->update(['active' =>1,'admin_check_status'=>1,'status' =>1,'finish_time'=>$finishTime,'cover'=>$cover]);
            // 激活商家用户信息
            (new AgentUser)->save(['active' =>1,'admin_check_status'=>1,'status' =>1,'finish_time'=>$finishTime],['agent_id'=>$agent_id]);
            return 1;
        });

    }


    /**
     * 移入移出回收站
     * @param bool $is_recycle
     * @return false|int
     */
    public function recycle($is_recycle = true)
    {
        return $this->save(['is_recycle' => (int)$is_recycle]);
    }

    /**
     * 软删除
     * @return false|int
     */
    public function setDelete()
    {
        return $this->transaction(function () {
            // 删除商家用户信息
            (new AgentUser)->setDelete($this['agent_id']);
            // 设置当前商城为已删除
            return $this->save(['is_delete' => 1]);
        });
    }



}